package cn.tk.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Created by denglw on 2021/5/27.<br/>
 * Desc: MD5散列算法实现
 */
public final class MD5Util {

    /**
     * MD5散列码生成.<br/>
     * @param encodeSrc 源串
     * @return MD5码
     */
    public static String md5(String encodeSrc) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        if (encodeSrc == null || encodeSrc.trim().length() == 0) {
            return "";
        }
        byte[] bytes = encodeSrc.getBytes(StandardCharsets.UTF_8);
        byte[] md5Bytes = md5.digest(bytes);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        // 拼接规则：appId + appSecret + timestamp + nonce
        String src = "tk" + "dGtAdGFpa2FuZ19jaGF0Ym90" + time+ "denglw";
        String md5 = md5(src);
        System.out.println(md5);
        System.out.println(time);
    }
}
